<?php


namespace App\Modules\Order\Repositories;


use App\Exceptions\NotFoundException;
use App\Models\OrderCancel;
use Flower\Core\Repository\Eloquent\BaseRepository;

class OrderCancelRepository extends BaseRepository
{
    public function model()
    {

        return OrderCancel::class;
    }

    public function isExisted($id)
    {
        $info = $this->find($id);
        if (empty($info)) {
            throw new NotFoundException(['msg' => '订单取消不存在']);
        }
        return $info;
    }

	/**
	 *  新增取消申请
	 * @param $orderId
	 * @param $canceler
	 * @param $reason
	 * @param int $status
	 * @return mixed
	 */
    public function addApply($orderId, $canceler, $reason, $status=0,$isRead=0)
    {

        $cancel = $this->model->where(['order_id' => $orderId, 'canceler' => $canceler])->orderBy('id','desc')->first();
        if (empty($cancel) ||  ($cancel->status == config('constant.cancelStatus.refuse')) || ($cancel->status == config('constant.cancelStatus.destroy'))) {
            $cancel = $this->create([
                'order_id'   => $orderId,
                'canceler'   => $canceler,
                'reason'     => $reason,
                'status'     => empty($status) ? config('constant.cancelStatus.going') : $status,
                'apply_time' => date('Y-m-d H:i:s'),
                'handle_time'=> date('Y-m-d H:i:s'),
                'is_read'    => $isRead
            ]);
        }
        return $cancel;
    }


    /**
     * 更新状态
     * @param $orderCancelId
     * @return mixed
     */
    public function updateOrderCancelStatus($orderCancelId, $status,$isRead=0)
    {
        return $this->update(['status' => $status, 'handle_time' => date('Y-m-d H:i:s', time()),'is_read'=>$isRead], $orderCancelId);
    }
}
